package client.comm.commlib.utils

import android.content.Context
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
import java.io.*

class StoreUtil {

    companion object {
        val set: HashMap<String, Serializable> by lazy { HashMap<String, Serializable>() }

        inline fun <reified T : Serializable> saveBean(context: Context, t: T) {

            try {
                val outStream =
                    context.openFileOutput(T::class.java.name, Context.MODE_PRIVATE)
                val oos = ObjectOutputStream(outStream)
                oos.writeObject(t)
                oos.flush()
                oos.close()
                set.put(T::class.java.name, t)
            } catch (e: IOException) {
                e.printStackTrace()
            }

        }

        inline fun <reified T : Serializable> getBean(context: Context): T? {
            if (set.containsKey(T::class.java.name)) return set.get(T::class.java.name) as T

            var t: T? = null
            var fis: FileInputStream? = null
            var ois: ObjectInputStream? = null
            try {
                val file = File(context.filesDir, T::class.java.name)
                if (file.exists()) {
                    fis = context.openFileInput(T::class.java.name)
                    ois = ObjectInputStream(fis)
                    t = ois.readObject() as T
                    set.put(T::class.java.name, t)
                } else {
                    return null
                }
            } catch (e: Exception) {
                return null
            } finally {
                fis?.close()
                ois?.close()
            }
            return t
        }
    }
}